'use client'

import React from 'react'
import { Spin, Progress } from 'antd'
import { LoadingOutlined } from '@ant-design/icons'
import { useUIStore } from '@/stores/uiStore'

// 全局加载遮罩
export const GlobalLoadingOverlay: React.FC = () => {
    const { loading } = useUIStore()

    if (!loading.global) {
        return null
    }

    return (
        <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
            <div className="bg-white rounded-lg p-8 flex flex-col items-center space-y-4 min-w-[200px]">
                <Spin
                    size="large"
                    indicator={<LoadingOutlined style={{ fontSize: 32 }} spin />}
                />
                <div className="text-gray-700 text-center">
                    <div className="font-medium">加载中...</div>
                    <div className="text-sm text-gray-500 mt-1">请稍候</div>
                </div>
            </div>
        </div>
    )
}

// 组件级加载指示器
interface ComponentLoadingProps {
    loading: boolean
    children: React.ReactNode
    tip?: string
    size?: 'small' | 'default' | 'large'
    overlay?: boolean
}

export const ComponentLoading: React.FC<ComponentLoadingProps> = ({
    loading,
    children,
    tip = '加载中...',
    size = 'default',
    overlay = true
}) => {
    if (!loading) {
        return <>{children}</>
    }

    if (overlay) {
        return (
            <div className="relative">
                {children}
                <div className="absolute inset-0 bg-white bg-opacity-75 flex items-center justify-center z-10">
                    <Spin size={size} tip={tip} />
                </div>
            </div>
        )
    }

    return (
        <div className="flex items-center justify-center p-8">
            <Spin size={size} tip={tip} />
        </div>
    )
}

// 进度条加载指示器
interface ProgressLoadingProps {
    percent: number
    status?: 'normal' | 'exception' | 'active' | 'success'
    showInfo?: boolean
    strokeColor?: string
    title?: string
    description?: string
}

export const ProgressLoading: React.FC<ProgressLoadingProps> = ({
    percent,
    status = 'active',
    showInfo = true,
    strokeColor,
    title,
    description
}) => {
    return (
        <div className="progress-loading p-6 bg-white rounded-lg shadow-sm border">
            {title && (
                <div className="mb-2">
                    <h4 className="font-medium text-gray-800">{title}</h4>
                    {description && (
                        <p className="text-sm text-gray-600 mt-1">{description}</p>
                    )}
                </div>
            )}
            <Progress
                percent={percent}
                status={status}
                showInfo={showInfo}
                strokeColor={strokeColor}
            />
        </div>
    )
}

// 骨架屏加载
interface SkeletonLoadingProps {
    rows?: number
    avatar?: boolean
    title?: boolean
    active?: boolean
    className?: string
}

export const SkeletonLoading: React.FC<SkeletonLoadingProps> = ({
    rows = 3,
    avatar = false,
    title = true,
    active = true,
    className = ''
}) => {
    return (
        <div className={`skeleton-loading ${className}`}>
            <div className="animate-pulse">
                <div className="flex space-x-4">
                    {avatar && (
                        <div className="rounded-full bg-gray-300 h-12 w-12"></div>
                    )}
                    <div className="flex-1 space-y-3">
                        {title && (
                            <div className="h-4 bg-gray-300 rounded w-3/4"></div>
                        )}
                        {Array.from({ length: rows }).map((_, index) => (
                            <div key={index} className="space-y-2">
                                <div className="h-3 bg-gray-300 rounded"></div>
                                <div className="h-3 bg-gray-300 rounded w-5/6"></div>
                            </div>
                        ))}
                    </div>
                </div>
            </div>
        </div>
    )
}

// 图像加载占位符
interface ImageLoadingPlaceholderProps {
    width?: number | string
    height?: number | string
    text?: string
    className?: string
}

export const ImageLoadingPlaceholder: React.FC<ImageLoadingPlaceholderProps> = ({
    width = '100%',
    height = 200,
    text = '加载影像中...',
    className = ''
}) => {
    return (
        <div
            className={`
                image-loading-placeholder 
                bg-gray-100 border-2 border-dashed border-gray-300 
                flex items-center justify-center
                ${className}
            `}
            style={{ width, height }}
        >
            <div className="text-center text-gray-500">
                <Spin size="large" />
                <div className="mt-2 text-sm">{text}</div>
            </div>
        </div>
    )
}

// 数据表格加载
interface TableLoadingProps {
    columns: number
    rows: number
    showHeader?: boolean
}

export const TableLoading: React.FC<TableLoadingProps> = ({
    columns,
    rows,
    showHeader = true
}) => {
    return (
        <div className="table-loading">
            <div className="animate-pulse">
                {showHeader && (
                    <div className="grid gap-4 mb-4" style={{ gridTemplateColumns: `repeat(${columns}, 1fr)` }}>
                        {Array.from({ length: columns }).map((_, index) => (
                            <div key={index} className="h-4 bg-gray-300 rounded"></div>
                        ))}
                    </div>
                )}
                {Array.from({ length: rows }).map((_, rowIndex) => (
                    <div key={rowIndex} className="grid gap-4 mb-3" style={{ gridTemplateColumns: `repeat(${columns}, 1fr)` }}>
                        {Array.from({ length: columns }).map((_, colIndex) => (
                            <div key={colIndex} className="h-3 bg-gray-200 rounded"></div>
                        ))}
                    </div>
                ))}
            </div>
        </div>
    )
}

// 加载状态管理Hook
export const useLoading = () => {
    const { loading, setGlobalLoading, setComponentLoading } = useUIStore()

    const showGlobalLoading = () => setGlobalLoading(true)
    const hideGlobalLoading = () => setGlobalLoading(false)

    const showComponentLoading = (component: string) => setComponentLoading(component, true)
    const hideComponentLoading = (component: string) => setComponentLoading(component, false)

    const isComponentLoading = (component: string) => loading.components[component] || false

    const withLoading = async <T,>(
        operation: () => Promise<T>,
        component?: string
    ): Promise<T> => {
        try {
            if (component) {
                showComponentLoading(component)
            } else {
                showGlobalLoading()
            }

            const result = await operation()
            return result
        } finally {
            if (component) {
                hideComponentLoading(component)
            } else {
                hideGlobalLoading()
            }
        }
    }

    return {
        loading,
        showGlobalLoading,
        hideGlobalLoading,
        showComponentLoading,
        hideComponentLoading,
        isComponentLoading,
        withLoading
    }
}

// 自动加载管理器
export const AutoLoadingManager: React.FC<{ children: React.ReactNode }> = ({ children }) => {
    const { loading } = useUIStore()

    return (
        <>
            {children}
            <GlobalLoadingOverlay />

            {/* 组件级加载状态显示 */}
            {Object.entries(loading.components).map(([component, isLoading]) =>
                isLoading && (
                    <div key={component} className="fixed bottom-4 left-4 z-40">
                        <div className="bg-white rounded-lg shadow-lg p-3 flex items-center space-x-2">
                            <Spin size="small" />
                            <span className="text-sm text-gray-600">
                                {component} 加载中...
                            </span>
                        </div>
                    </div>
                )
            )}
        </>
    )
}

export default {
    GlobalLoadingOverlay,
    ComponentLoading,
    ProgressLoading,
    SkeletonLoading,
    ImageLoadingPlaceholder,
    TableLoading,
    AutoLoadingManager
}